package com.ruoyi.edh.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.aliyuncs.ecs.model.v20140526.DescribePriceResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeRenewalPriceResponse;
import com.egzosn.pay.ali.bean.AliTransactionType;
import com.egzosn.pay.common.bean.PayOrder;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.OrderException;
import com.ruoyi.common.exception.PayException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.edh.domain.*;
import com.ruoyi.edh.domain.bo.OrderPayBo;
import com.ruoyi.edh.mapper.*;
import com.ruoyi.edh.service.IEdhMasterOrderAliPayService;
import com.ruoyi.system.mapper.SysUserMapper;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.function.SupplierUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @description:支付成功订单修改业务类
 * @author: 梁东宸
 * @time: 2020/9/7 2:23 下午
 */
@Service
public class EdhMasterOrderAliPayServiceImpl implements IEdhMasterOrderAliPayService {
    //主订单
    @Autowired
    private EdhMasterOrderMapper edhMasterOrderMapper;
    //子订单
    @Autowired
    private EdhOrderMapper edhOrderMapper;
    //商品对象
    @Autowired
    private EdhGoodsMapper goodsMapper;
    //用户对象
    @Autowired
    private SysUserMapper sysUserMapper;
    //收益表
    @Autowired
    private EdhProfitMapper profitMapper;
    //团队收益占比
    @Autowired
    private EdhCommissionMixMapper mixMapper;
    /**
     *
     *
     * @description:
     * @param masterOrderNo
     * @return:
     * @author: 梁东宸
     * @time: 2020/9/7 11:21 上午
     */
    @Override
    public PayOrder masterOrderAliPay(String masterOrderNo) {
        EdhMasterOrder edhMasterOrder=new EdhMasterOrder();
        edhMasterOrder.setMasterOrderNo(masterOrderNo);
        List<EdhMasterOrder> edhMasterOrders = edhMasterOrderMapper.selectEdhMasterOrderList(edhMasterOrder);
        EdhMasterOrder edhMasterOrder1 = edhMasterOrders.get(0);
        //获取商品实付总价
        BigDecimal actualAmount = edhMasterOrder1.getActualAmount();
        //获取运费价格
        BigDecimal shipping = edhMasterOrder1.getShipping();
        //算出应付价格
        BigDecimal sum = actualAmount.add(shipping);
        return new PayOrder("易订货商品购买", masterOrderNo, sum , masterOrderNo, AliTransactionType.PAGE);
    }

    /**
     * @param masterOrderNo
     * @Author: 周爱鸿
     * @Description: 根据订单号支付
     * @CreateDate: 2020/11/13 9:51
     */
    @Override
    public AlipayTradeAppPayResponse masterOrderAliPay1(String masterOrderNo) throws Exception {
        EdhMasterOrder edhMasterOrder=new EdhMasterOrder();
        edhMasterOrder.setMasterOrderNo(masterOrderNo);
        List<EdhMasterOrder> edhMasterOrders = edhMasterOrderMapper.selectEdhMasterOrderList(edhMasterOrder);
        EdhMasterOrder edhMasterOrder1 = edhMasterOrders.get(0);
        //获取商品实付总价
        BigDecimal actualAmount = edhMasterOrder1.getActualAmount();
        //获取运费价格
        BigDecimal shipping = edhMasterOrder1.getShipping();
        //算出应付价格
        BigDecimal sum = actualAmount.add(shipping);
        if ("0.00".equals(sum.toString())){
            sum = new BigDecimal(0.01);
        }
        return Factory.Payment.App().pay("易订货商品购买",masterOrderNo,sum.toString());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean payMentSuccess(OrderPayBo orderPayBo) throws PayException, OrderException, ParseException {
        Boolean add=true;
        //查询主订单列表
        EdhMasterOrder edhMasterOrder=new EdhMasterOrder();
        edhMasterOrder.setMasterOrderNo(orderPayBo.getOutTradeNo());
        List<EdhMasterOrder> edhMasterOrders = edhMasterOrderMapper.selectEdhMasterOrderList(edhMasterOrder);
        EdhMasterOrder edhMasterOrder1 = edhMasterOrders.get(0);
        //实付金额
        BigDecimal actualAmount = edhMasterOrder1.getActualAmount();
        //获得运费
        BigDecimal shipping = edhMasterOrder1.getShipping();
        //算出总金额
        BigDecimal sum = actualAmount.add(shipping);
        if (sum.compareTo(orderPayBo.getOriginalPrice())!=0){
            throw new PayException("支付金额和订单金额不一致");
        }
        edhMasterOrder1.setSellerId(orderPayBo.getSellerId());
        edhMasterOrder1.setTradeNo(orderPayBo.getTradeNo());
        //根据主订单查询出子订单列表
        EdhOrder edhOrder=new EdhOrder();
        edhOrder.setMasterOrderId(edhMasterOrder1.getId().toString());
        List<EdhOrder> edhOrders = edhOrderMapper.selectEdhOrderList(edhOrder);

        for (EdhOrder order : edhOrders) {
            //当订单处于待付款状态时才修改状态
            if ("0".equals(order.getOrderStatus())){
                //修改状态为已付款
                order.setOrderStatus("1");
                order.setPaymentType(orderPayBo.getPaymentType());
                order.setPaymentStatus("1");
                order.setPaymentTime(orderPayBo.getTimestamp());
                int order1 = edhOrderMapper.updateEdhOrder(order);
                if (order1<1){
                    add=false;
                }
            }else {
                throw new OrderException("订单状态异常");
            }
        }
        //获得组队收益分成比
       /* List<EdhCommissionMix> edhCommissionMixes = mixMapper.selectEdhCommissionMixList(null);
        BigDecimal mix = edhCommissionMixes.get(0).getMix();
        for (EdhOrder order : edhOrders) {
            EdhProfit edhProfit=new EdhProfit();
            EdhGoods edhGoods = goodsMapper.selectEdhGoodsById(Long.valueOf(order.getGoodsId()));
            //获得订单的用户
            SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(order.getUserId()));
            //订单用户的1级邀请人
            SysUser inviter = sysUserMapper.selectUserById(sysUser.getInvitees());
            if (StringUtils.isNotNull(inviter) &&  "1".equals(inviter.getTeamLeader()))
            {
                //查看团长收益是否存在
                EdhProfit edhProfit1 = profitMapper.selectEdhProfitById(inviter.getUserId());
                if (edhProfit1!=null){
                    //直卖收益
                    BigDecimal myBenefits = edhProfit1.getMyBenefits();
                    BigDecimal rebate = edhGoods.getRebate();
                    //本次订单的收益
                    rebate = rebate.multiply(BigDecimal.valueOf(order.getGoodsNumber()));
                    //设置直卖收益
                    edhProfit1.setMyBenefits(myBenefits.add(rebate));
                    //获得总收益
                    BigDecimal allBenefits = edhProfit1.getAllBenefits();
                    //设置总收益
                    edhProfit1.setAllBenefits(allBenefits.add(rebate));
                    //设置今日收益
                    BigDecimal todayBenefits = edhProfit1.getTodayBenefits();
                    edhProfit1.setTodayBenefits(todayBenefits.add(rebate));
                    int i = profitMapper.updateEdhProfit(edhProfit1);
                    if (i<1) {
                        add = false;
                    }
                }else {
                    EdhProfit edhProfit2=new EdhProfit();
                    BigDecimal rebate = edhGoods.getRebate();
                    //本次订单的收益
                    rebate = rebate.multiply(BigDecimal.valueOf(order.getGoodsNumber()));
                    edhProfit2.setMyBenefits(rebate);
                    edhProfit2.setAllBenefits(rebate);
                    edhProfit2.setTodayBenefits(rebate);
                    edhProfit2.setCreateBy(inviter.getUserId().toString());
                    edhProfit2.setCreateTime(new Date());
                    profitMapper.insertEdhProfit(edhProfit2);
                }

                //获得订单用户团长的邀请人信息
                SysUser sysUser1 = sysUserMapper.selectUserById(inviter.getInvitees());
                if ("1".equals(sysUser1.getTeamLeader())){

                    //查看团长收益是否存在
                    EdhProfit edhProfit3 = profitMapper.selectEdhProfitById(sysUser1.getUserId());
                    if (edhProfit1!=null){
                        //直卖收益
                        BigDecimal teamBenefits = edhProfit3.getTeamBenefits();
                        BigDecimal rebate = edhGoods.getRebate();
                        //本次订单的收益
                        rebate = rebate.multiply(BigDecimal.valueOf(order.getGoodsNumber()));
                        //设置团队收益占比计算出团队收益
                        rebate=rebate.multiply(mix);
                        //设置团队收益
                        edhProfit3.setTeamBenefits(teamBenefits.add(rebate));
                        //获得总收益
                        BigDecimal allBenefits = edhProfit3.getAllBenefits();
                        //设置总收益
                        edhProfit3.setAllBenefits(allBenefits.add(rebate));
                        //设置今日收益
                        BigDecimal todayBenefits = edhProfit3.getTodayBenefits();
                        edhProfit3.setTodayBenefits(todayBenefits.add(rebate));
                        int i = profitMapper.updateEdhProfit(edhProfit1);
                        if (i<1) {
                            add = false;
                        }
                    }else {
                        EdhProfit edhProfit4=new EdhProfit();
                        BigDecimal rebate = edhGoods.getRebate();
                        //本次订单的收益
                        rebate = rebate.multiply(BigDecimal.valueOf(order.getGoodsNumber()));
                        //设置团队收益占比计算出团队收益
                        rebate=rebate.multiply(BigDecimal.valueOf(0.2));
                        edhProfit4.setTeamBenefits(rebate);
                        edhProfit4.setAllBenefits(rebate);
                        edhProfit4.setTodayBenefits(rebate);
                        edhProfit4.setCreateBy(inviter.getUserId().toString());
                        edhProfit4.setCreateTime(new Date());
                        profitMapper.insertEdhProfit(edhProfit4);
                    }

                }

            }

        }*/
        int order = edhMasterOrderMapper.updateEdhMasterOrder(edhMasterOrder1);
        if (order<1){
            add=false;
        }
        return add;
    }
}
